package com.jinxin.platform.cdqzsqacs.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.cdqzsqacs.bean.CdqzsqacsDevice;
import com.jinxin.platform.cdqzsqacs.bean.CdqzsqacsOpenRecord;
import com.jinxin.platform.cdqzsqacs.bean.bo.RecordInfo;
import com.jinxin.platform.cdqzsqacs.bean.bo.UserInfo;
import com.jinxin.platform.cdqzsqacs.bean.gaEntity.Ga_mjjcjlxx;
import com.jinxin.platform.cdqzsqacs.bean.gaEntity.Ga_rlzpxx;
import com.jinxin.platform.cdqzsqacs.common.Constant;
import com.jinxin.platform.cdqzsqacs.mapper.CdqzsqacsDeviceMapper;
import com.jinxin.platform.cdqzsqacs.mapper.CdqzsqacsOpenRecordMapper;
import com.jinxin.platform.cdqzsqacs.rpc.SysUserRpc;
import com.jinxin.platform.cdqzsqacs.service.impl.GaUploadAsyncService;
import com.jinxin.platform.cdqzsqacs.task.ResultEntity;
import com.jinxin.platform.cdqzsqacs.utils.BizUtil;
import com.jinxin.platform.cdqzsqacs.utils.DateUtil;
import com.jinxin.platform.cdqzsqacs.utils.ImageUtils;
import com.jinxin.platform.cdqzsqacs.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-05-21
 * @Author: Lingnan
 **/
@RestController
@RequestMapping("/unAuth")
@Slf4j
public class QzsqUnauthController {
    @Autowired
    private CdqzsqacsOpenRecordMapper openRecordMapper;
    @Autowired
    private CdqzsqacsDeviceMapper deviceMapper;
    @Autowired
    private SysUserRpc sysUserRpc;
    @Autowired
    private GaUploadAsyncService gaUploadAsyncService;

    @PostMapping("/api/downdata/saveUserInfo.html")
    public Map<String, Object> saveUserInfo(HttpServletRequest request){
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(
                    request.getInputStream(), StandardCharsets.UTF_8));
            StringBuffer sb = new StringBuffer("");
            String temp;
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
            br.close();
            String acceptjson = sb.toString();
            log.info("---------------智慧门禁上报:"+ acceptjson);
            String jsonNwe = JSONObject.parseObject(acceptjson).get("Recards").toString().replace("//","" );
            List<RecordInfo> infoDOS = JSONObject.parseArray(jsonNwe,RecordInfo.class );
            for (RecordInfo info: infoDOS){
                String devMAC = info.getDevMAC();
                String id = BizUtil.convMac216(devMAC)+ info.getId();
                CdqzsqacsOpenRecord selInfo = openRecordMapper.selectByKey(id);
                if(null == selInfo){
                    CdqzsqacsOpenRecord infoDO = new CdqzsqacsOpenRecord();
                    int ioType = info.getIOType();
                    String openType;
                    switch (ioType){
                        case 1: openType = "刷卡";break;
                        case 2: openType = "人脸识别";break;
                        case 3: openType = "视频对接";break;
                        case 4: openType = "网络";break;
                        case 5: openType = "按钮";break;
                        case 6: openType = "无线";break;
                        default: openType = "未知";break;
                    }
                    infoDO.setOpenType(openType);
                    infoDO.setId(id);
                    long ioTime = info.getIOTime();
                    LocalDateTime openTime = DateUtil.getDateTimeOfTimestamp(ioTime * 1000);
                    infoDO.setOpenTime(openTime);
                    String userID = info.getUserID()+"";
                    infoDO.setOpenUserId(userID +"");
                    HashMap param = new HashMap();
                    param.put("deviceMac",devMAC.toLowerCase());//这里是大写的需要转成小写
                    CdqzsqacsDevice device = deviceMapper.selectOne(param);
                    StringBuffer fkSource = new StringBuffer();
                    String deviceId = "",communityId = "";
                    if(device != null){
                        deviceId = device.getId();
                        infoDO.setSerialNum(device.getSerialNum());
                        communityId = device.getCommunityId();
                        infoDO.setCommunityId(communityId);
                        String communityName = device.getCommunityName();
                        infoDO.setCommunityName(communityName);
                        String nickName = device.getNickName();
                        String deviceName = StringUtils.isEmpty(nickName) ? device.getDeviceName() : nickName;
                        infoDO.setDeviceName(deviceName);
                        fkSource.append(communityName);
                    }
                    // 通过userId查询用户信息
                    UserInfo userInfo = sysUserRpc.getUserInfoById(userID);
                    String userName = "",cardNo = "";
                    if(userInfo != null){
                        userName = userInfo.getUserName();
                        cardNo = userInfo.getUserCard();
                        infoDO.setOpenUser(userName);
                        infoDO.setCardNo(cardNo);
                        infoDO.setPhone(userInfo.getUserPhone());
                        String personType = "未知";
                        String userType = userInfo.getUserType();
                        if(!StringUtils.isEmpty(userType)){
                            switch (userType){
                                case "10":personType = "管理员";break;
                                case "11":personType = "业主";break;
                                case "12":personType = "家属";break;
                                case "13":personType = "租客";break;
                                case "14":personType = "其他";break;
                                case "15":personType = "工作人员";break;
                                default:personType = "未知";break;
                            }
                        }
                        infoDO.setPersonType(personType);
                        fkSource.append(userInfo.getUserBlockName());
                        //fkSource.append(userInfo.getUserUnitName()); // 去掉单元
                        fkSource.append(userInfo.getUserRoomName());
                    }
                    infoDO.setSource(fkSource.toString());
                    openRecordMapper.insert(infoDO);
                    String cardNo1 = infoDO.getCardNo();
                    String cjsj = (int) (System.currentTimeMillis() / 1000) + "";
                    // 身份证号不存在推送到公安人脸抓拍表
                    String pushJson = "",typeStr;
                    String photoUrl = info.getCamPhotoUrl();//得到是相对路径
                    StringBuffer url = request.getRequestURL();
                    String serverUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
                    String imgUrl = serverUrl + photoUrl;
                    log.info("抓拍图片路径: " +imgUrl);
                    // 耗时的操作放在异步
                    String capBase64 = "";
//                    if(!StringUtils.isEmpty(photoUrl)){
//                        capBase64 = ImageUtils.getBase64ByImgUrl(serverUrl + photoUrl);
//                    }
                    String xqxxbz = StringUtils.isEmpty(communityId) ? "": communityId.split(",")[0];
                    if(StringUtils.isEmpty(cardNo1)){
                        typeStr = "ga_rlzpxx";
                        List<Ga_rlzpxx> rlzpxxList = new ArrayList<>();
                        Ga_rlzpxx rlzpxx = Ga_rlzpxx.builder().RLZPXXBZ(id).SPTXXXYYSXDXBZ(userID)
                                .SPTXXXCJFSDM("").NLSX("").NLXX("").XBDM("").MZDM("").SFBKRY_PDBZ("").SFGZRY_PDBZ("")
                                .CJSBXXBZ(deviceId).ZSJ_ZXDHZB("").ZSJ_ZXDZZB("").YXJ_ZXDHZB("").YXJ_ZXDZZB("").TXR_RS("")
                                .SFDKZ_PDBZ("").ZMTZDM("").SFJSY_PDBZ("").PDYJTZDM("").XBTZDM("").SSZZTZDM("").XSZZTZDM("")
                                .ZXTZDM("").SY_YS("").KUZ_YS("").XZ_YS("").MZ_YS("").KZ_YS("").TP(capBase64).CJSJ(cjsj)
                                .XQXXBZ("noTimeFormatRequired@"+xqxxbz).SJLY(Constant.DEVICE_SYLY).OPERATE_TYPE("add").build();
                        rlzpxxList.add(rlzpxx);
                        pushJson = JSON.toJSONString(rlzpxxList);
                    }else {
                        typeStr = "ga_mjjcjlxx";
                        List<Ga_mjjcjlxx> mjjcxxList = new ArrayList<>();
                        Ga_mjjcjlxx cjsbxx = Ga_mjjcjlxx.builder().MJJCJLXXBZ(id).XM(userName).GMSFZHM(cardNo)
                                .KMRLZP(capBase64).PZH("").MJDBH("").SK_RQSJ(openTime.toString()).MCZT("1")
                                .GLDMJ_CJSBXXBZ(deviceId).SFTG_PDBZ("1").KMFSDM("4").KMJG("1").MJSJLX("0")
                                .CJSJ(cjsj).XQXXBZ("noTimeFormatRequired@"+xqxxbz).SJLY(Constant.DEVICE_SYLY).OPERATE_TYPE("add").build();
                        mjjcxxList.add(cjsbxx);
                        pushJson = JSON.toJSONString(mjjcxxList);
                    }
                    // 推送到公安平台
                    gaUploadAsyncService.gaUploadData(typeStr, pushJson,true,imgUrl);
                    log.info("上传成功1条门禁进出数据至公安平台");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("status",1);
        resMap.put("msg","请求成功");
        resMap.put("uninsert", new ArrayList<>());
        return resMap;
    }

    @RequestMapping("/api/downdata/getConfigs.html")
    public Map<String,Object> getConfigs(String controllersn){
        log.info("设备发出/api/downdata/getConfigs.html请求，设备Mac: " + controllersn) ;
        if(StringUtils.isEmpty(controllersn)){return null;}
        HashMap param = new HashMap();
        param.put("deviceMac",controllersn.toLowerCase());
        CdqzsqacsDevice device = deviceMapper.selectOne(param);
        if(device == null){
            return null;
        }
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("name",device.getNickName());
        resMap.put("controllersn",controllersn);
        String typeId = device.getTypeId();
        // 设备类型，0：无效[删除设备后为 0]；1：室内机；2：单元机；3：小区机；默认小区机:3
        if(StringUtils.isEmpty(typeId)){
            resMap.put("type",Constant.DEVICE_TYPE_COMMUNITY);
        }else {
            int type;
            switch (typeId){
                case "1":type = Constant.DEVICE_TYPE_COMMUNITY;break;
                case "2":type = Constant.DEVICE_TYPE_UNIT;break;
                default:type = 0;break;
            }
            resMap.put("type",type);
        }
        int score = device.getScore() != null ? device.getScore() : 80;
        resMap.put("score",score);
        int actlive = device.getActlive() != null && device.getActlive() == 0 ? 0 : 1;
        resMap.put("actlive", actlive);
        int advertvolume = device.getAdvertvolume() != null ? device.getAdvertvolume() : 5;
        resMap.put("advertvolume", advertvolume);
        int ttsvolume = device.getTtsvolume() != null ? device.getTtsvolume() : 100;
        resMap.put("ttsvolume", ttsvolume);
        int livenessthreshold = device.getLivenessthreshold() != null ? device.getLivenessthreshold() : 50;
        resMap.put("livenessthreshold", livenessthreshold);
        //resMap.put("domain", device.getDomain());
        resMap.put("notifytitle", device.getNotifytitle());
        resMap.put("companyname", device.getCompanyname());
        resMap.put("qrcodeurl", device.getQrcodeurl());
        resMap.put("description", device.getDescription());
        resMap.put("callurl", device.getCallurl());
        return resMap;
    }

    @PostMapping("/api/downdata/getAllNotices.html")
    public JSONArray getAllNotices(String controllersn){
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", Utils.getRandom6());
        jsonObject.put("content", Utils.getUuid());
        jsonObject.put("status", 0);
        jsonObject.put("starttime", System.currentTimeMillis());
        jsonObject.put("overtime", System.currentTimeMillis());
        jsonArray.add(jsonObject);
        return jsonArray;
    }
}
